//@ts-nocheck
import React, { useEffect, useImperativeHandle } from 'react'
import * as echarts from 'echarts/lib/echarts'
import { GridComponent } from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { ChartsInstance } from '../../Charts/Bar/interface'
import { CanvasRenderer } from 'echarts/renderers'
import './index.less'

echarts.use([GridComponent, BarChart, CanvasRenderer])

let echartsInstance: any

interface IProps {
  data?: any
  chartId?: string
  chartRef?: React.MutableRefObject<ChartsInstance>
}

const BasicCylinderChart: React.FC<IProps> = ({ data, chartId, chartRef }) => {
  useEffect(() => {
    echartsInstance = echarts.init(document.getElementById(chartId || 'cylinder-chart'))
  }, [])

  useEffect(() => {
    if (echartsInstance && data.length > 0) setOptions()
  }, [data])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return echartsInstance
    }
  }))
  const setOptions = () => {
    const cityies = data.map((item) => item.name)
    const values = data.map((item) => item.value)
    echartsInstance.setOption({
      color: '#5A86FF',
      grid: {
        left: 20,
        right: 20,
        top: 16,
        bottom: 0,
        containLabel: true
      },
      textStyle: {
        fontFamily: 'ngFangSC-Regular',
        fontSize: '12px',
        fontWeight: 400,
        color: '#8B98A9'
      },
      xAxis: {
        type: 'category',
        data: cityies,
        axisTick: {
          show: false,
          alignWithLabel: true
        },
        axisLabel: {
          interval: 0,
          formatter: function (value) {
            let str = ''
            let num = 8 // 每行显示字数
            let valLength = value.length // 该项x轴字数
            let rowNum = Math.ceil(valLength / num) // 行数

            if (rowNum > 1) {
              for (let i = 0; i < rowNum; i++) {
                let temp = ''
                let start = i * num
                let end = start + num

                temp = value.substring(start, end) + '\n'
                str += temp
              }
              return str
            } else {
              return value
            }
          }
        },
        axisLine: {
          lineStyle: {
            color: '#DCE0E6'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#ECEEF1'
          }
        }
      },
      series: [
        {
          data: values,
          type: 'bar',
          barWidth: 16
        }
      ]
    })
  }
  return <div className="cylinder-chart" id={chartId || 'cylinder-chart'} />
}
export default (BasicCylinderChart)
